<template>
  <div class="article-create-page">
    <van-nav-bar
      title="创作文章"
      left-text="返回"
      right-text="发布"
      left-arrow
      @click-left="onClickLeft"
      @click-right="publishArticle"
    />
    
    <div class="editor-container">
      <van-field
        v-model="articleTitle"
        placeholder="请输入文章标题"
        class="title-input"
        :rules="[{ required: true, message: '请输入文章标题' }]"
        maxlength="50"
        show-word-limit
      />
      
      <div class="editor-toolbar">
        <div class="toolbar-item" @click="insertFormat('bold')">
          <van-icon name="font-o" />
        </div>
        <div class="toolbar-item" @click="insertFormat('italic')">
          <van-icon name="font" />
        </div>
        <div class="toolbar-item" @click="insertFormat('heading')">
          <van-icon name="label-o" />
        </div>
        <div class="toolbar-item" @click="insertFormat('list')">
          <van-icon name="bars" />
        </div>
        <div class="toolbar-item" @click="insertFormat('link')">
          <van-icon name="link" />
        </div>
        <div class="toolbar-item" @click="insertImage">
          <van-icon name="photo-o" />
        </div>
      </div>
      
      <van-field
        v-model="articleContent"
        type="textarea"
        placeholder="请输入文章内容"
        class="content-input"
        :rules="[{ required: true, message: '请输入文章内容' }]"
        rows="12"
        autosize
      />
      
      <div class="article-options">
        <div class="option-section">
          <div class="section-title">文章分类</div>
          <van-dropdown-menu>
            <van-dropdown-item v-model="category" :options="categoryOptions" />
          </van-dropdown-menu>
        </div>
        
        <div class="option-section">
          <div class="section-title">文章标签</div>
          <div class="tags-container">
            <van-tag 
              v-for="(tag, index) in tags" 
              :key="index" 
              closeable 
              type="primary" 
              @close="removeTag(index)"
              class="tag-item"
            >
              {{ tag }}
            </van-tag>
            
            <van-button 
              size="small" 
              type="default" 
              icon="plus" 
              @click="showTagInput = true"
              v-if="tags.length < 5"
            >
              添加标签
            </van-button>
          </div>
        </div>
        
        <div class="option-section">
          <div class="section-title">封面图片</div>
          <van-uploader
            v-model="coverImages"
            :max-count="1"
            :after-read="afterReadCover"
            :before-delete="beforeDeleteCover"
          />
        </div>
        
        <div class="option-section">
          <div class="section-title">发布设置</div>
          <van-cell-group inset>
            <van-cell title="允许评论">
              <template #right-icon>
                <van-switch v-model="allowComment" size="24" />
              </template>
            </van-cell>
            <van-cell title="公开可见">
              <template #right-icon>
                <van-switch v-model="isPublic" size="24" />
              </template>
            </van-cell>
          </van-cell-group>
        </div>
      </div>
    </div>
    
    <div class="action-buttons">
      <van-button type="default" block @click="saveAsDraft">保存草稿</van-button>
    </div>
    
    <!-- 添加标签弹窗 -->
    <van-popup
      v-model:show="showTagInput"
      position="bottom"
      round
      :style="{ height: '30%' }"
    >
      <div class="tag-popup">
        <div class="popup-header">
          <div class="popup-title">添加标签</div>
          <van-icon name="cross" @click="showTagInput = false" />
        </div>
        
        <div class="tag-input-container">
          <van-field
            v-model="newTag"
            placeholder="请输入标签名称（最多10个字符）"
            maxlength="10"
            show-word-limit
          >
            <template #button>
              <van-button 
                size="small" 
                type="primary" 
                :disabled="!newTag.trim()"
                @click="addTag"
              >
                添加
              </van-button>
            </template>
          </van-field>
          
          <div class="tag-suggestions">
            <div class="suggestion-title">推荐标签</div>
            <div class="suggestion-list">
              <van-tag 
                v-for="tag in suggestedTags" 
                :key="tag"
                @click="selectSuggestedTag(tag)"
                class="suggestion-tag"
              >
                {{ tag }}
              </van-tag>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
    
    <!-- 图片选择器（隐藏） -->
    <input 
      type="file" 
      ref="imageInput" 
      accept="image/*" 
      style="display: none;" 
      @change="onImageSelected" 
    />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { useUserStore } from '../../store/user'
import { generateId } from '../../utils/common'

const router = useRouter()
const userStore = useUserStore()
const imageInput = ref(null)

// 文章内容
const articleTitle = ref('')
const articleContent = ref('')
const category = ref('tech')
const tags = ref([])
const coverImages = ref([])
const allowComment = ref(true)
const isPublic = ref(true)

// 分类选项
const categoryOptions = [
  { text: '技术', value: 'tech' },
  { text: '生活', value: 'life' },
  { text: '旅行', value: 'travel' },
  { text: '美食', value: 'food' },
  { text: '健康', value: 'health' },
  { text: '其他', value: 'other' }
]

// 标签相关
const showTagInput = ref(false)
const newTag = ref('')
const suggestedTags = [
  'Vue', 'React', 'JavaScript', 'CSS', 'HTML', 
  '前端', '后端', '移动开发', '云计算', 'AI'
]

// 返回上一页
const onClickLeft = () => {
  if (articleTitle.value || articleContent.value) {
    showDialog({
      title: '提示',
      message: '是否保存为草稿？',
      showCancelButton: true,
      confirmButtonText: '保存',
      cancelButtonText: '不保存'
    }).then(() => {
      saveAsDraft()
      router.back()
    }).catch(() => {
      router.back()
    })
  } else {
    router.back()
  }
}

// 添加标签
const addTag = () => {
  if (!newTag.value.trim()) {
    showToast('标签不能为空')
    return
  }
  
  if (tags.value.includes(newTag.value.trim())) {
    showToast('标签已存在')
    return
  }
  
  if (tags.value.length >= 5) {
    showToast('最多添加5个标签')
    return
  }
  
  tags.value.push(newTag.value.trim())
  newTag.value = ''
  showTagInput.value = false
}

// 移除标签
const removeTag = (index) => {
  tags.value.splice(index, 1)
}

// 选择推荐标签
const selectSuggestedTag = (tag) => {
  if (tags.value.includes(tag)) {
    showToast('标签已存在')
    return
  }
  
  if (tags.value.length >= 5) {
    showToast('最多添加5个标签')
    return
  }
  
  tags.value.push(tag)
  showTagInput.value = false
}

// 处理封面图片上传
const afterReadCover = (file) => {
  // 实际项目中应该上传到服务器
  // 这里仅做演示
  showToast('封面上传成功')
}

// 处理封面图片删除
const beforeDeleteCover = () => {
  return new Promise((resolve) => {
    showDialog({
      title: '提示',
      message: '是否删除封面图片？',
      showCancelButton: true
    }).then(() => {
      resolve(true)
    }).catch(() => {
      resolve(false)
    })
  })
}

// 插入格式化文本
const insertFormat = (type) => {
  const textarea = document.querySelector('.content-input textarea')
  if (!textarea) return
  
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  const selectedText = articleContent.value.substring(start, end)
  
  let formattedText = ''
  
  switch (type) {
    case 'bold':
      formattedText = `**${selectedText || '粗体文本'}**`
      break
    case 'italic':
      formattedText = `*${selectedText || '斜体文本'}*`
      break
    case 'heading':
      formattedText = `\n## ${selectedText || '标题'}\n`
      break
    case 'list':
      formattedText = `\n- ${selectedText || '列表项'}\n`
      break
    case 'link':
      formattedText = `[${selectedText || '链接文本'}](https://example.com)`
      break
    default:
      formattedText = selectedText
  }
  
  articleContent.value = 
    articleContent.value.substring(0, start) + 
    formattedText + 
    articleContent.value.substring(end)
  
  // 设置光标位置
  setTimeout(() => {
    textarea.focus()
    textarea.setSelectionRange(start + formattedText.length, start + formattedText.length)
  }, 0)
}

// 插入图片
const insertImage = () => {
  imageInput.value.click()
}

// 图片选择回调
const onImageSelected = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    showToast('请选择图片文件')
    return
  }
  
  // 检查文件大小（限制为5MB）
  if (file.size > 5 * 1024 * 1024) {
    showToast('图片大小不能超过5MB')
    return
  }
  
  // 读取文件为Data URL
  const reader = new FileReader()
  reader.onload = (e) => {
    // 插入图片标记
    const imageMarkdown = `\n![图片](${e.target.result})\n`
    
    const textarea = document.querySelector('.content-input textarea')
    if (!textarea) return
    
    const start = textarea.selectionStart
    
    articleContent.value = 
      articleContent.value.substring(0, start) + 
      imageMarkdown + 
      articleContent.value.substring(start)
    
    // 设置光标位置
    setTimeout(() => {
      textarea.focus()
      textarea.setSelectionRange(start + imageMarkdown.length, start + imageMarkdown.length)
    }, 0)
  }
  reader.readAsDataURL(file)
  
  // 清空文件选择器，以便再次选择同一文件
  event.target.value = ''
}

// 保存为草稿
const saveAsDraft = () => {
  if (!articleTitle.value.trim()) {
    showToast('请输入文章标题')
    return
  }
  
  // 实际项目中应该调用API保存草稿
  // 这里仅做演示
  showToast('已保存为草稿')
  
  // 模拟保存成功后的跳转
  setTimeout(() => {
    router.push('/profile/articles')
  }, 1500)
}

// 发布文章
const publishArticle = () => {
  if (!articleTitle.value.trim()) {
    showToast('请输入文章标题')
    return
  }
  
  if (!articleContent.value.trim()) {
    showToast('请输入文章内容')
    return
  }
  
  // 实际项目中应该调用API发布文章
  // 这里仅做演示
  showDialog({
    title: '发布文章',
    message: '确定要发布这篇文章吗？',
    showCancelButton: true
  }).then(() => {
    showToast('文章发布成功')
    
    // 模拟发布成功后的跳转
    setTimeout(() => {
      router.push(`/blog/${generateId()}`)
    }, 1500)
  }).catch(() => {
    // 取消操作
  })
}
</script>

<style lang="scss" scoped>
.article-create-page {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: calc(var(--tabbar-height) + 80px);
  
  .editor-container {
    padding: 16px;
    
    .title-input {
      margin-bottom: 16px;
      
      :deep(.van-field__control) {
        font-size: 18px;
        font-weight: 600;
      }
    }
    
    .editor-toolbar {
      display: flex;
      background-color: var(--background-color-light);
      border-radius: 4px 4px 0 0;
      border: 1px solid var(--border-color);
      border-bottom: none;
      
      .toolbar-item {
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 40px;
        cursor: pointer;
        
        &:hover {
          background-color: var(--background-color);
        }
        
        .van-icon {
          font-size: 18px;
          color: var(--text-color-secondary);
        }
      }
    }
    
    .content-input {
      margin-bottom: 16px;
      border: 1px solid var(--border-color);
      border-radius: 0 0 4px 4px;
      
      :deep(.van-field__control) {
        min-height: 300px;
        font-family: 'Courier New', Courier, monospace;
        line-height: 1.6;
      }
    }
    
    .article-options {
      margin-top: 24px;
      
      .option-section {
        margin-bottom: 20px;
        
        .section-title {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 8px;
          color: var(--text-color);
        }
        
        .tags-container {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          
          .tag-item {
            margin-right: 8px;
            margin-bottom: 8px;
          }
        }
      }
    }
  }
  
  .action-buttons {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    padding: 12px 16px;
    padding-bottom: calc(12px + var(--tabbar-height));
    background-color: var(--background-color-light);
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    z-index: 10;
    
    .van-button {
      flex: 1;
      margin: 0 4px;
    }
  }
  
  .tag-popup {
    padding: 16px;
    
    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      .popup-title {
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .tag-input-container {
      .tag-suggestions {
        margin-top: 16px;
        
        .suggestion-title {
          font-size: 14px;
          color: var(--text-color-secondary);
          margin-bottom: 8px;
        }
        
        .suggestion-list {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          
          .suggestion-tag {
            cursor: pointer;
            margin-bottom: 8px;
          }
        }
      }
    }
  }
}
</style> 